<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件

//发起一个post
function curl_post($url='',$data=[]){
    $data = is_array($data) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $info = curl_exec($ch);

    if(curl_errno($ch)){
        return [
            "err" => 1,
            "msg" => 'Errno'.curl_error($ch),
        ];
    }
    curl_close($ch);
    return [
        "err" => 0,
        "data"=> $info,
    ];
}

function getImageUrl($url=''){
    if( !empty($url) ){
        $url = substr($url,0,4)=="https" ? $url : "https://".$_SERVER["HTTP_HOST"].$url;
    }
    return $url;
}


/**
 * GET 请求
 * @param string $url
 */
function http_get($url){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}

/**
 * POST 请求
 * @param string $url
 * @param array $param
 * @param boolean $post_file 是否文件上传
 * @return string content
 */
function http_post($url,$param,$post_file=false){
    $oCurl = curl_init();
    if(stripos($url,"https://")!==FALSE){
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
    }
    if (is_string($param) || $post_file) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach($param as $key=>$val){
            $aPOST[] = $key."=".urlencode($val);
        }
        $strPOST =  join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($oCurl, CURLOPT_POST,true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if(intval($aStatus["http_code"])==200){
        return $sContent;
    }else{
        return false;
    }
}

/**
 * 秒转时间字符
 * @param $time
 * @return string
 */
function time_to_str($time){
    $d = floor($time / (3600*24));
    $h = floor(($time % (3600*24)) / 3600);
    $m = floor((($time % (3600*24)) % 3600) / 60);
    if($d>'0'){
        //return $d.'天'.$h.'小时'.$m.'分';
        return $d.'天';
    }else{
        if($d<0 || $h<0 || $m<0){
            return '已到期';
        }else{
            if($h!='0'){
                return $h.'小时'.$m.'分';
            }else{
                return $m.'分';
            }
        }
    }
}

/**
 * @param $length
 * @return string
 * 用户注册生成的密码盐
 */
function com_randomkeys($length)
{
    $key = '';
//        $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    $pattern = '1234567890ABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    for($i=0;$i<$length;$i++)
    {
        $key .= $pattern{mt_rand(0,35)};
    }
    return $key;
}

//添加系统日志
/**
 * @param $content
 */
function add_sys_log($content){
    $admin_id = session('user_info')['id'];
    $make_model = CONTROLLER_NAME;
    $create_time = time();
    $request  = \think\Request::instance();
    $ip = $request->ip();
    $data = [
        'admin_id'=>$admin_id,
        'make_model'=>$make_model,
        'make_content'=>$content,
        'ip'=>$ip,
        'create_time'=>$create_time,
        'admin_id'=>$admin_id,
    ];
    M('sys_log')->insert($data);
}
function downloadExcel($strTable,$filename)
{
    ob_end_clean();
    //header('Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Type:application/vnd.ms-excel');
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=".$filename."_".date('Y-m-d').".xls");
    header('Expires:0');
    header('Pragma:public');
    echo '<html><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'.$strTable.'</html>';
}

/**
 * @param $insert_arr为插入消息的关联数组 数组键名由以下组成
 *          键名          值类型   说明
 *          com_id       int     企业id
 *          user_id      int     用户id
 *          cate_type    int     消息类型  1审核消息 2任务消息 3公告消息 4积分奖扣消息 5催审 6奖扣任务通知
 *          type         int     数据类型 1公告  2任务 3积分奖扣 4请假
 *          title        str     标题
 *          relation_id  int     数据类型关联表id  包含 任务id,公告id,积分奖扣id,请假申请id
 *          name         str     名称  (事件主题,任务名称,公告名称,请假名称)
 *          record_name  str     记录人
 *          first_name   str     初审人
 *          last_name    str     终审人
 * @return int|string
 */
function user_message_insert($insert_arr){
    $insert_arr['create_time'] = time();
    $r = db('com_user_message')->insert($insert_arr);
    //ji_guang_push('xxxxx');
    return $r;
}

/**
 * @param 极光设备标识  待测试
 */
function ji_guang_push($user_id,$message){
    require EXTEND_PATH.'/ji_guang_push/autoload.php';
    $conf = config('ji_guang');//获取极光配置
    $client = new JPush\Client($conf['appKey'], $conf['masterSecret'], null);
    try {
        $response = $client->push()
            ->setPlatform(array('ios', 'android'))
//            ->addRegistrationId($registration_id)
            ->addAlias($user_id)
            ->setNotificationAlert('Hi, JPush')
            ->iosNotification('Hello IOS', array(
                'sound' => 'sound.caf',
                // 'badge' => '+1',
                // 'content-available' => true,
                // 'mutable-content' => true,
                'category' => 'jiguang',
                'extras' => array(
                    'key' => 'value',
                    'jiguang'
                ),
            ))
            ->androidNotification('Hello Android', array(
                'title' => 'hello jpush',
                // 'builder_id' => 2,
                'extras' => array(
                    'key' => 'value',
                    'jiguang'
                ),
            ))
            ->message('message content', array(
                'title' => 'hello jpush',
                // 'content_type' => 'text',
                'extras' => array(
                    'key' => 'value',
                    'jiguang'
                ),
            ))
            ->options(array(
                // True 表示推送生产环境，False 表示要推送开发环境；如果不指定则默认为推送开发环境
                'apns_production' => false,
            ))
            ->send();
        file_put_contents(ROOT_PATH.'ji_guang_err_log.txt', "成功-------".$response);
    } catch (\Exception $e) {
        file_put_contents(ROOT_PATH.'ji_guang_err_log.txt', "失败-------".$e->getMessage());
    }
}

/**
 * 获取传入时间范围的时间数组 超过三个月则返回最近三个月
 * @param $dateStr  时间范围字符串 如 2012-05-08 - 2012-08-08
 * @return array    返回开始和结束时间段
 */
function month3($dateStr = ''){
    $time = [];
    $currentTime = time();
    $cyear = floor(date("Y",$currentTime));
    $cMonth = floor(date("m",$currentTime));
    for($i=0;$i<3;$i++){
        $nMonth = $cMonth-$i;
        $cyear = $nMonth == 0 ? ($cyear-1) : $cyear;
        $nMonth = $nMonth <= 0 ? 12+$nMonth : $nMonth;
        $time[] = $cyear.'-'.$nMonth;
    }
    $return_data = [strtotime($time[2]), time()];//近三个月
    if($dateStr){
        $return_data = [];
        $dateArr = explode(' - ', $dateStr);
        $start    = new \DateTime($dateArr[0]);
        $end      = new \DateTime($dateArr[1]);
        $interval = \DateInterval::createFromDateString('1 month');  //按月获取
        $period   = new \DatePeriod($start, $interval, $end);
        $month_day = 0;
        foreach ($period as $dt) {
            $month_day++;
        }
    }
    if($dateStr && $month_day > 3){
        $return_data = [strtotime($time[2]), time()];//近三个月
    }elseif($dateStr){
        $return_data = [strtotime($dateArr[0]), strtotime($dateArr[1])];
    }
    return $return_data;
}

function ldump($data){
    error_log(print_r($data,1).PHP_EOL, 3, "F:/PHPTutorial/log/123.log");
//    error_log(print_r($data,1).PHP_EOL, 3, "/home/www/ldump.log");
}